<?php
declare (strict_types=1);

namespace app\common\model;

use think\Collection;
use Exception;

class Ad extends CommonBase
{
    public function getAllAd(array $where = [], int $limit = 0): Collection
    {
        $where['is_delete'] = config('status.mysql.table_normal');
        $db                 = $this->where($where)->order('sort asc');
        if ($limit) {
            return $db->limit($limit)->select();
        }

        return $db->select();
    }

    public function getAdList(int $page = 1, int $limit = 10, array $where = []): Collection
    {
        $where['is_delete'] = config('status.mysql.table_normal');
        $offset             = ($page - 1) * $limit;
        return $this->where($where)->order('sort asc')->limit($offset, $limit)->select();
    }

    public function getAdCount(array $where = []): int
    {
        $where['is_delete'] = config('status.mysql.table_normal');
        return $this->where($where)->count();
    }

    public function findAdById(int $id)
    {
        return $this->where(['id' => $id, 'is_delete' => config('status.mysql.table_normal')])->find();
    }

    /**
     * @throws Exception
     */
    public function addAd(array $data): bool
    {
        try {
            $this->startTrans();
            $data['is_delete'] = config('status.mysql.table_normal');
            $this->save($data);

            $id = $this->getLastInsID();
            if (!empty($data['image'])){
                $this->name('attachment')->where(['url_md5' => md5($data['image'])])->update([
                    'relation_type' => self::AD_ATTACHMENT_TYPE,
                    'relation_id'   => $id,
                    'updated_at'    => date('Y-m-d H:i:s'),
                ]);
            }

            $this->commit();
            return true;
        } catch (Exception $e) {
            $this->rollback();
            throw new Exception($e->getMessage());
        }
    }

    /**
     * @throws Exception
     */
    public function updateAd(int $id, array $data): bool
    {
        try {
            $this->startTrans();
            $data['updated_at'] = date('Y-m-d H:i:s');
            $this->where(['id' => $id])->save($data);
            if(!empty($data['image'])){
                $this->name('attachment')->where(['url_md5' => md5($data['image'])])->update([
                    'relation_type' => self::AD_ATTACHMENT_TYPE,
                    'relation_id'   => $id,
                    'updated_at'    => date('Y-m-d H:i:s'),
                ]);
            }
            $this->commit();
            return true;
        } catch (Exception $e) {
            $this->rollback();
            throw new Exception($e->getMessage());
        }
    }

    /**
     * @throws Exception
     */
    public function deleteAd(int $id): bool
    {
        try {
            $this->startTrans();
            $this->where(['id' => $id])->save(['is_delete' => config('status.mysql.table_delete')]);
            $this->name('attachment')->where(['relation_id' => $id, 'relation_type' => self::AD_ATTACHMENT_TYPE])->update([
                'is_delete'  => config('status.mysql.table_delete'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);
            $this->commit();
            return true;
        } catch (Exception $e) {
            $this->rollback();
            throw new Exception($e->getMessage());
        }
    }

    /**
     * @throws Exception
     */
    public function batchAdSort(array $data): bool
    {
        try {
            $this->startTrans();
            foreach ($data as $id => $sort) {
                $this->where('id', $id)->update(['sort' => $sort]);
            }
            $this->commit();
            return true;
        } catch (Exception $e) {
            $this->rollback();
            throw new Exception($e->getMessage());
        }
    }

    /**
     * @throws Exception
     */
    public function batchDeleteAd(array $ids): bool
    {
        try {
            $this->startTrans();
            $this->where([['id', 'in', $ids]])->save([
                'is_delete'  => config('status.mysql.table_delete'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);

            $this->name('attachment')->where([['relation_id', 'in', $ids], 'relation_type' => self::AD_ATTACHMENT_TYPE])->update([
                'is_delete'  => config('status.mysql.table_delete'),
                'updated_at' => date('Y-m-d H:i:s'),
            ]);

            $this->commit();
            return true;
        } catch (\Exception $e) {
            $this->rollback();
            throw new Exception($e->getMessage());
        }
    }
}
